/*  
 * cafe-customdatepicker.js
 * @Author :      GUORUI
 * @CreateDate :  2017年10月27日
 * Copyright (c) 2017, NRIET.　
 * 日期控件
 */

;define(function(){
	/**
	 * 创建控件界面
	 */
	function getNodeHtml(cfg){
		var wrapper = $('<div>').addClass("customdatepicker");
		var $cdleft = $('<div>').addClass("cd-left");
		var $cdright = $('<div>').addClass("cd-right");
		var $cdlult = $('<ul>');
		var $cdlustime = $('<li>').append($('<i>').addClass("cd-icon"))
                                   .append($('<span>').addClass("cd-time-label").text(new Date(cfg.startTime).format("yyyy-MM-dd")));
		var $cdluetime = $('<li>').append($('<i>').addClass("cd-icon"))
                                    .append($('<span>').addClass("cd-time-label").text(new Date(cfg.endTime).format("yyyy-MM-dd")));
        $cdlult.append($cdlustime).append($cdluetime);
		var $cdlulb = $('<ul>');
		$.each([{type : "week", text : "最近一周"},{type : "month", text : "最近一月"},{type : "year", text : "最近一年"}],function(){
            $cdlulb.append($('<li>').attr("type",this.type).text(this.text));
		});
        $cdleft.append($cdlult).append($cdlulb);
        var $cdrtable = $('<table>');
        var $cdrftr = $('<tr>');
        var $cdrftd = $('<td>').attr({"colspan" : 2,"rowspan" : 2});
        $cdrftd.append($('<i>').addClass("cafe-ifont cafe-ic-iconfontxiangyou"))
            .append($('<span>').text(new Date(cfg.endTime).format("yyyy年")))
            .append($('<i>').addClass("cafe-ifont cafe-ic-iconfontxiangyou"));
        $cdrftr.append($cdrftd);
        $.each([
        	{val : "01", text : "1月"}, {val : "02", text : "2月"},{val : "03", text : "3月"},
            {val : "04", text : "4月"},{val : "05", text : "5月"},{val : "06", text : "6月"},
			{val : "07", text : "7月"},{val : "08", text : "8月"},{val : "09", text : "9月"},
			{val : "10", text : "10月"},{val : "11", text : "11月"},{val : "12", text : "12月"}], function(){
        	var $td = $('<td>').attr("val",this.val).text(this.text);
        	if(new Date(cfg.endTime).format("MM") == this.val){
                $td.addClass("active");
			}
            $cdrftr.append($td);
		});
        $cdrtable.append($cdrftr);
        var $cdrtr = $('<tr>');
        $.each([
        	{val : "01,02,03", text : "第一季度"},{val : "04,05,06", text : "第二季度"},
			{val : "07,08,09", text : "第三季度"},{val : "10,11,12", text : "第四季度"}], function(){
            $cdrtr.append($('<td>').attr({"colspan" : "3", "val" : this.val}).text(this.text));
		});
        $cdrtable.append($cdrtr);
        $cdright.append($cdrtable);
        wrapper.append($cdleft).append($cdright);
		return wrapper;
	}
	/**
	 * 绑定事件
	 */
	function _eves($drop,cfg){
        $drop.off().on("click",".cd-left>ul:first>li",function(){//日期选择
            dateselect = CafeJS.Dateselect({
                appendTo : $(this).find("span.cd-time-label"),
                dateFmt : "yyyy-MM-dd",
                curDate : $(this).find("span.cd-time-label").text()
            });
        }).on("click",".cd-left>ul:last>li",function(){//快速选择最近时间
            if(!$(this).hasClass("active")){
                $drop.find('.cd-right td:gt(0)').removeClass("active");
                $(this).siblings().removeClass("active");
                $(this).addClass("active");
                var date = new Date();
                date.setDate(date.getDate()-1);
                $drop.find("ul:first>li:last>span").text(date.format("yyyy-MM-dd"));
                if("week" == $(this).attr("type")){
                    date.setDate(date.getDate()-7);
                }else if("month" == $(this).attr("type")){
                    date.setMonth(date.getMonth()-1);
                }else if("year" == $(this).attr("type")){
                    date.setFullYear(date.getFullYear()-1);
                }
                $drop.find("ul:first>li:first>span").text(date.format("yyyy-MM-dd"));

                if($.isFunction(cfg.call)){
                    cfg.call();
                }
            }
		}).on("click",".cd-right tr:first span",function(){//选择年份
            $drop.find('.cd-left>ul:last>li').removeClass("active");
            $(this).siblings('ul').remove();
            var year = new Date();
            var $yearSelect = $('<ul>');
            for(var i = 0; i < 10; i++){
                $yearSelect.append($('<li>').text(year.format(("yyyy年"))));
                year.setFullYear(year.getFullYear()-1);
            }
            $(this).after($yearSelect);

            var that = this;
            $(this).siblings('ul').find("li").unbind().bind("click",function(){
                $drop.find('.cd-right td:gt(0)').removeClass("active");
                $(that).text($(this).text());
                $drop.find("ul:first>li:first>span").text($(this).text().substr(0,4) + "-01-01");
                $drop.find("ul:first>li:last>span").text($(this).text().substr(0,4) + "-12-31");
                $(this).parent().remove();

                if($.isFunction(cfg.call)){
                    cfg.call();
                }
            });
            $(this).siblings('ul').unbind("mouseleave").bind("mouseleave",function(){
                $(that).one('blur',function(){
                    $(that).siblings('ul').remove();
                });
            });
        }).on("click",".cd-right i",function () {//增加或减少年份
            $drop.find('.cd-left>ul:last>li').removeClass("active");
            var selYear = $(this).siblings('span').text().substr(0,4);
            var year = new Date(selYear);
            if($(this).next().is(":visible")){//减一年
                year.setFullYear(year.getFullYear() - 1);
            }else if($(this).prev().is(":visible")){//加一年
                year.setFullYear(year.getFullYear() + 1);
            }
            $(this).siblings('span').text(year.format("yyyy年"));
            var $stime = $drop.find("ul:first>li:first>span");
            var $etime = $drop.find("ul:first>li:last>span");
            $stime.text(year.getFullYear() + $stime.text().substr(4));
            $etime.text(year.getFullYear() + $etime.text().substr(4));

            if($.isFunction(cfg.call)){
                cfg.call();
            }
        }).on("click", ".cd-right td:gt(0)", function(){//选择月份或季度
            if(!$(this).hasClass("active")){
                $drop.find('.cd-left>ul:last>li').removeClass("active");
                $(this).closest("table").find("td").removeClass("active");
                $(this).addClass("active");
                var val = $(this).attr("val").split(",");
                var selYear = $(this).closest(".cd-right").find('span').text().substr(0,4);
                var date = new Date();
                date.setFullYear(selYear);
                if(val.length > 1){
                    date.setMonth(val[2],1);
                    date.setDate(date.getDate()-1);
                    $drop.find("ul:first>li:first>span").text(selYear+"-"+val[0]+"-01");
                    $drop.find("ul:first>li:last>span").text(selYear+"-"+val[2]+"-"+date.getDate());
                }else{
                    date.setMonth(val,1);
                    date.setDate(date.getDate()-1);
                    $drop.find("ul:first>li:first>span").text(selYear+"-"+val+"-01");
                    $drop.find("ul:first>li:last>span").text(selYear+"-"+val+"-"+date.getDate());
                }

                if($.isFunction(cfg.call)){
                    cfg.call();
                }
            }
		}).on("mousemove",".cd-right tr:first td:gt(0)",function(e){//拖动选择月份
            e.preventDefault();
            var m = $(this).closest("tr").data("month");
            if(2 != e.button && !$.isEmptyObject(m)){
                var offx = event.pageX - m.x;
                var i = Math.floor(offx/$(this).width());
                $(this).closest("tr").find("td:eq("+m.index+")").addClass("active");
                $(this).closest("tr").find("td:not(:eq("+m.index+"))").removeClass("active");
                if(i > 0){
                    $(this).closest("tr").find("td:gt("+m.index+"):lt("+i+")").addClass("active");
                }else{
                    $(this).closest("tr").find("td:lt("+(m.index+1)+"):gt("+(m.index+i)+")").addClass("active");
                }
                var $activeMonth = $drop.find(".cd-right tr:first td:gt(0).active");
                if($activeMonth.length > 0){
                    var selYear = $(this).closest(".cd-right").find('span').text().substr(0,4);
                    var date = new Date();
                    date.setFullYear(selYear);
                    date.setMonth($activeMonth.last().attr("val"),1);
                    date.setDate(date.getDate()-1);
                    $drop.find("ul:first>li:first>span").text(selYear+"-"+$activeMonth.first().attr("val")+"-01");
                    $drop.find("ul:first>li:last>span").text(selYear+"-"+$activeMonth.last().attr("val")+"-"+date.getDate());
                }
            }
		}).on("mousedown",".cd-right tr:first td:gt(0)",function(e){
		    if(2 != e.button){
                $drop.find('.cd-left>ul:last>li').removeClass("active");
                $(this).closest("table").find("td").removeClass("active");
                $(this).closest("tr").data("month",{x : event.pageX,index : $(this).index()});
            }
        }).on("mouseup",".cd-right tr:first td:gt(0)",function(e){
            if(2 != e.button) {
                var $tr = $(this).closest("tr");
                if (!$.isEmptyObject($tr.data("month"))) {
                    $tr.removeData("month");
                    var $activeMonth = $drop.find(".cd-right tr:first td:gt(0).active");
                    if ($activeMonth.length > 0 && $.isFunction(cfg.call)) {
                        cfg.call();
                    }
                }
            }
        }).on("mouseleave",".cd-right tr:first",function(){//鼠标离开月份选择区
            if(!$.isEmptyObject($(this).data("month"))){
                $(this).removeData("month");
                if($.isFunction(cfg.call)){
                    cfg.call();
                }
            }
        });
		$(top.document).on('mousedown',function(ev){
			if(0 == $(ev.target).closest(".customdatepicker").length){
                $(".cd-right tr:first td:first ul").remove();
                if(dateselect){
                    dateselect.remove();
                }
			}
		});
	}
	var dateselect = null;
	var CFCustomDatepicker = function(settings){
		var options = {
				appendTo: '',//控件所在容器
				startTime : null,//起始时间
				endTime : null,//结束时间
				call : null//回调函数
		};
		this.config = $.extend({},options, settings);
		this.$drop = getNodeHtml(this.config);
		_eves(this.$drop,this.config);
		if(this.config.appendTo){
			$(this.config.appendTo).empty().append(this.$drop);
		}
	}

    CFCustomDatepicker.prototype = {
        getVal : function(){
            return {
                startTime : this.$drop.find("ul:first>li:first>span").text(),
                endTime : this.$drop.find("ul:first>li:last>span").text()
            };
        },
        setVal : function(startTime,endTime){
            this.$drop.find("ul:first>li:first>span").text(startTime);
            this.$drop.find("ul:first>li:last>span").text(endTime);
        }
	};
	
	CafeJS.CustomDatepicker = function(settings){
		var drop =new CFCustomDatepicker(settings);
		return drop;
	}
});